<template>
  <div class="role-manage-wrapper">
    <div class="role-tree-wrapper">
      <el-card class="box-card">
        <div slot="header">
          <span class="box-card-title">角色（单选）</span>
          <button class="add-first-node-btn" type="text" @click="() => showModal($event,'add')">
            <span class="icon add-first-node-icon"></span>新增一级节点
          </button>
        </div>
        <tree-view ref="role" :treeData="roleTree" :expandOnClickNode="false" :showCheckbox="true" :checkStrictly="true" :isIcon="true" :showFlag="showFlag"
                  :operateLevel="operateLevel" @on-check-change="roleCheckChange" @on-add="showModal($event,'add')" @on-delete="showModal($event,'delete')">
        </tree-view>
      </el-card>
    </div>
    <div class="permission-tree-wrapper">
      <el-card class="box-card">
        <div slot="header">
          <span class="box-card-title">菜单配置（多选）</span>
        </div>
        <tree-view ref="menu" :treeData="permissionTree" :showCheckbox="true" :checkOnClickNode="true" :treeDefaultCheckedKeys="selectedMenu"
                   @on-check-change="permissionCheckChange">
        </tree-view>
        <div class="save-config">
          <button class="save-config-btn" :disabled="checkRole.length == 0 || checkMenu.length == 0" @click="saveConfig()">
            <span class="icon save-config-icon"></span>保存配置
          </button>
        </div>
      </el-card>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :show-close="showCloseFlag" width="500px">
      <div class="dialog-container" v-if="dialogTitle === '重新登录'">
        <div class="login-box">
          配置过权限后需要重新登录后生效，<span class="login-time">{{times}}s</span>后跳转到登录页！
        </div>
      </div>
      <div class="dialog-container" v-else-if="dialogTitle === '删除节点'">确定要删除这个节点吗？</div>
      <div class="dialog-container" v-else>
        <label>节点名称：</label>
        <div class="node-name-input">
          <el-input size="small" placeholder="请输入节点名称" v-model="currentNodeName" clearable>
          </el-input>
        </div>
      </div>
      <span slot="footer" class="dialog-footer" v-if="dialogTitle !== '重新登录'">
        <el-button type="primary" @click="save" v-if="dialogTitle === '删除节点'">确定</el-button>
        <el-button type="primary" @click="save" v-if="dialogTitle !== '删除节点'">保存</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: 'RoleManage',
    components:{},
    data() {
      let baseUrl = managerRemoteGatewayUrl;
      return {
        urls: {
          getRoleTreeUrl: baseUrl + '/org/tree', //获取角色树,
          getServerListUrl: baseUrl + '/menu/server/list', //获取所有服务
          getMenuUrl: baseUrl + '/menu/tree', //获取右侧所有的菜单树
          saveUrl: baseUrl + '/org/menu/edit', //为角色配置菜单权限
          editServerUrl: baseUrl + '/org/server/edit', //角色和服务关联
          getRoleMenuUrl: baseUrl + '/org/menu/list', //获取某个角色下拥有的菜单
          deleteRolesUrl: baseUrl + '/org/delete', //删除角色
          operationRoleUrl: baseUrl + '/org/add', //修改、添加角色路径一样，只是请求方式不同（put,post）
        },
        roleTree: [],
        permissionTree: [],
        checkRole: [],
        checkMenu: [],
        dialogTitle: '',
        dialogVisible: false,
        currentNodeName: '',
        nodeId: '',
        selectedMenu: [],
        systemOption: [],
        serverId: '',
        systemOptionLabel: [],
        times: 4,
        showCloseFlag: true,
        showFlag:{
          isAddShow: true,
          isDeleteShow: true
        },
        operateLevel:{
          add:[1],
          delete:[1,2]
        }
      }
    },
    methods: {
      //获取角色树
      getTreeData() {
        let me = this;
        this.httpRequest('get',this.urls.getRoleTreeUrl,{},{
          hideSuccessTip: true,
          ignoreEmptyData: true,
          fullSuccess: true,
        }).then(res => {
          if (res.value.children && res.value.children.length != 0) {
            me.roleTree = me.treeEditLevel(res.value.children,1);
          }
        });
      },
      treeEditLevel(data, level) {
        return data.map((d) => {
          let obj = this.cloneObj(d);
          obj.level = level;
          obj.children && (obj.children.length != 0) && (obj.children = this.treeEditLevel(obj.children, level + 1));
          return obj;
        })
      },
      //只能选中一个节点
      roleCheckChange(e) {
        this.checkRole = e.checkedNodes;
        if (e.isChecked) {
          if (this.checkRole.length >= 1) {
            this.$refs.role.$refs.tree.setCheckedNodes([e.data]);
            this.getRoleMenu(e.data.id);
          }
        }
      },
      //点击角色获取角色配置过的菜单
      getRoleMenu(id) {
        let me = this;
        this.selectedMenu = [];
        this.httpRequest('get',`${this.urls.getRoleMenuUrl}?orgid=${id}`,{},{
          hideSuccessTip: true,
          ignoreEmptyData: true,
          fullSuccess: true,
        }).then(res => {
          if (res.value.children && res.value.children.length != 0) {me.menuGroup(res.value.children);}
          setTimeout(function () {
            me.$refs.menu.$refs.tree.setCheckedKeys(me.selectedMenu);//获取已经设置的资源后渲染
          }, 100);
        });
      },
      menuGroup(menu){
        menu.forEach((d) => {
          if(d.children && d.children.length !== 0){
            this.menuGroup(d.children);
          }else{
            d.selected && this.selectedMenu.push(d.id);
          }
        })
      },
      //获取子系统
      getServerList() {
        let me = this;
        this.permissionTree = [];
        this.httpRequest('get',this.urls.getServerListUrl,{},{
          hideSuccessTip: true,
          ignoreEmptyData: true,
          fullSuccess: true,
        }).then(res => {
          me.systemOption = me.cloneObj(res.value);
          me.systemOptionLabel = [];
          res.value.forEach((d) => {
            me.systemOptionLabel.push(d.label);
            me.getMenuData(d);
          })
        });
      },
      //根据子系统id获取菜单，拼接成菜单树
      getMenuData(server) {
        let me = this;
        let tree = [];
        this.httpRequest('get',`${this.urls.getMenuUrl}?serverid=${server.value}`,{},{
          hideSuccessTip: true,
          ignoreEmptyData: true,
          fullSuccess: true,
        }).then(res => {
          if (res.value.children && res.value.children.length !== 0) {
            tree = me.cloneObj(res.value);
            tree.label = server.label;
            tree["id"] = server.value;
            me.permissionTree.push(tree);
          }
        });
      },
      //操作角色树
      showModal(e,str) {
        let node = e ? e.node : undefined;
        if (str === 'add') {
          if (node === undefined) {
            this.dialogTitle = '新增一级节点';
          } else {
            this.dialogTitle = '新增节点';
            this.nodeId = node.key;
          }
          this.currentNodeName = '';
        } else if (str === 'edit') {
          this.dialogTitle = '编辑节点';
          this.currentNodeName = node.data.label;
          this.nodeId = node.key;
        } else if (str === 'delete') {
          this.dialogTitle = '删除节点';
          this.nodeId = node.key;
        } else {
          return;
        }
        this.dialogVisible = true;
        this.showCloseFlag = true;
      },
      save() {
        let param = {name: this.currentNodeName},type = "post",url = this.urls.operationRoleUrl;
        if(this.dialogTitle === '新增节点'){
          param["pid"] = this.nodeId;
        }else if(this.dialogTitle === '编辑节点'){
          param["id"] = this.nodeId;
          type = 'put';
        }else if(this.dialogTitle === '删除节点'){
          url = `${this.urls.deleteRolesUrl}?orgid=${this.nodeId}`;
          type = 'delete';
          param = {};
        }
        let me = this;
        this.httpRequest(type,url,param,{
          ignoreEmptyData: true,
          fullSuccess: true,
        }).then(res => {
          me.getTreeData();
          me.getServerList();
          me.dialogVisible = false;
          me.showCloseFlag = true;
          me.dialogTitle === '删除节点' && (me.permissionTree = []);
          me.message(me,'success',res.message);
        });
      },
      //选择菜单树
      permissionCheckChange() {
        this.checkMenu = this.$refs.menu.$refs.tree.getCheckedNodes();
      },
      setDisabled(data, status) {
        data.forEach((d) => {
          d['disabled'] = status;
          if (d.children && d.children.length != 0) {
            d.children = this.setDisabled(d.children, status);
          }
        });
        return data;
      },
      //角色和服务关联
      editServerOrg() {
        let me = this,param = [];
        this.checkMenu.forEach((d, i) => {
          if(d.data){
            if(d.data.subsystem){
              if(me.systemOptionLabel.includes(d.data.subsystem)){
                !param.includes(d.data.serverId) && param.push(d.data.serverId);
              }
            }
          }else{
            if(me.systemOptionLabel.includes(d.label)){
              me.systemOption.forEach((s) => {
                if(s.label == d.label){
                  let val = s.value;
                  !param.includes(val) && param.push(val);
                }
              })
            }
          }
        });
        let orgId = this.checkRole[0].id;
        this.httpRequest('put',`${this.urls.editServerUrl}?orgid=${orgId}`,param,{
          ignoreEmptyData: true,
          fullSuccess: true,
        }).then(res => {});
      },
      //保存配置
      saveFun() {
        let me = this, param = [],orgId = this.checkRole[0].id;
        this.checkMenu.forEach((d, i) => {
         if(!me.systemOptionLabel.includes(d.label)){
           param.push(d.id);
         }
        });
        this.httpRequest('put',`${this.urls.saveUrl}?orgid=${orgId}`,param,{
          ignoreEmptyData: true,
          fullSuccess: true,
        }).then(res => {
          me.message(me, 'success', '保存成功');
          me.dialogTitle = "重新登录";
          me.dialogVisible = true;
          me.showCloseFlag = false;
          me.getLogin();
        });
      },
      //保存配置（调用两个接口）
      saveConfig() {
        this.editServerOrg();
        this.saveFun();
      },
      getLogin(){
        let me = this,setTime;
        this.times--;
        if(this.times > 0){
          setTime = setTimeout(function () {
            me.getLogin();
          },1000);
        }else{
          clearTimeout(setTime);
          this.dialogVisible = false;
          this.$router.push({path: '/login'});
        }
      }
    },
    mounted() {
      this.getTreeData();
      this.getServerList();
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  @import '../../../assets/styles/base_style';
  .role-manage-wrapper {
    width: 100%;
    height: 100%;
    .icon {
      display: inline-block;
      background: url("../../../assets/images/systemmanage/permission_save_config.png") no-repeat;
      width: 16px;
      height: 16px;
      position: relative;
      top: 3px;
      left: -5px;
    }
    .box-card-title {
      font-size: 16px;
      color: $fontColor333;
      font-weight: bold;
    }
    .permission-btn {
      color: #fff;
      background: $btnBackground;
      width: 140px;
      border: none;
      border-radius: 3px;
      cursor: pointer;
    }
    .role-tree-wrapper {
      float: left;
      width: 41%;
      margin-right: 10px;
      height: calc(100%);
      min-width: 300px;
      .add-first-node-btn {
        @include btnStyle(14px, 30px);
        position: absolute;
        right: 20px;
        top: 10px;
        .add-first-node-icon {
          background: url("../../../assets/images/systemmanage/permission_add_first_menu.png") no-repeat;
        }
      }
    }
    .permission-tree-wrapper {
      float: left;
      height: calc(100%);
      width: calc(100% - 41% - 10px);
      .save-config {
        text-align: center;
        padding: 30px 0;
        border-top: 1px solid #e1e1e1;
        .save-config-btn:disabled {
          background: #7ebbfb;
          cursor: not-allowed;
        }
        .save-config-btn {
          @include btnStyle(16px, 34px);
          .save-config-icon {
            background: url("../../../assets/images/systemmanage/permission_save_config.png") no-repeat;
          }
        }
      }
    }
    .box-card {
      height: 100%;
    }
  }
  .dialog-container:after {
    @include clearFloat;
  }
  .dialog-container {
    label {
      margin-bottom: 0;
      float: left;
      width: 100px;
      text-align: right;
      height: 30px;
      line-height: 30px;
      font-size: 16px;
    }
    .node-name-input {
      float: left;
      width: calc(100% - 100px);
      height: 30px;
      line-height: 30px;
    }
    .login-box{
      font-size: 16px;
      .login-time{
        color: red;
        font-weight: bold;
      }
    }
  }
</style>
<style rel="stylesheet/scss" lang="scss">
  @import "../../../assets/styles/base_style";
  .role-manage-wrapper {
    .el-card__body {
      height: calc(100% - 50px);
      padding: 0px;
    }
    .el-card__header {
      background: #EFF3FE;
      border: 1px solid #e1e1e1;
      height: 52px;
      padding: 15px 20px;
      position: relative;
    }
  }
</style>
